package com.xingkong.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.comet4j.core.CometContext;
import org.comet4j.core.CometEngine;

import com.xingkong.behavior.model.BehaviorModel;

public class RealTimeMessageListener implements ServletContextListener {
        private static final String CHANNEL = "realtimemessage";
        public void contextInitialized(ServletContextEvent arg0) {
                CometContext cc = CometContext.getInstance();
                cc.registChannel(CHANNEL);//注册应用的channel
                Thread helloAppModule = new Thread(new RealTimeMessageAppModule(), "RealTimeMessageAppModule");
                helloAppModule.setDaemon(true);
                helloAppModule.start();
        }

        class RealTimeMessageAppModule implements Runnable {
        	private boolean stop=false;
                public void run() {
                        while (true) {
                                try {
                                        Thread.sleep(1000);
                                } catch (Exception ex) {
                                        ex.printStackTrace();
                                }
                                CometEngine engine = CometContext.getInstance().getEngine();
                                engine.sendToAll(CHANNEL, BehaviorModel.getRealTimeMessage());
                        }
                }
				public boolean isStop() {
					return stop;
				}
				public void setStop(boolean stop) {
					this.stop = stop;
				}
        }

        public void contextDestroyed(ServletContextEvent arg0) {

        }
}
